#!/bin/sh
#
# This script converts pure image PDF files into djvu formats
#
# NB: this script will only converts pure images in PDF files
# no texts would be converted.

CMD_PDFIMAGES=`which pdfimages`
CMD_CJB2=`which cjb2`

if [ -x "${CMD_PDFIMAGES}" ]; then
	echo "### Good, you have XPDF installed, now proceeding..."
	echo ""
else
	echo "### Warning:"
	echo "###	You don't have XPDF! Consider installing the latest"
	echo "###	XPDF utilities."
	echo ""
	exit 1
fi

if [ -x "${CMD_CJB2}" ]; then
	echo "### Good, you have djvulibre installed, now proceeding..."
	echo ""
else
	echo "### Warning:"
	echo "###	You dont' have djvulibre! Consider installing the latest"
	echo "###	djvulibre utilities."
	echo ""
	exit 1
fi

for pdf_file in *.pdf; do

	djvu_root=${pdf_file%.pdf}
	echo "### Now proceed to '${pdf_file}'..."
	pdfimages $pdf_file $djvu_root

	for file in *.pbm; do
		file_mid=${file#${djvu_root}-}
		file_num=${file_mid%.pbm}
		if [ ${file_num} -le 999 ]; then
			mv $file ${djvu_root}-00${file_num}.pbm
		else
			mv $file ${djvu_root}-0${file_num}.pbm
		fi
	done

	for pbm_file in *.pbm; do
		djvu_file=${pbm_file%.pbm}.djvu
		echo "### Converting '${pbm_file}' to '${djvu_file}'...."
		cjb2 -losslevel -0 -dpi 300 $pbm_file $djvu_file
	done

	djvm -c ${djvu_root} *.djvu
	rm -f *.djvu *.pbm
	install -d djvu_files
	mv $djvu_root djvu_files/${djvu_root}.djvu
	djvu_root=
	djvu_file=
	pdf_file=
	pbm_file=
	file=
	file_mid=
	file_num=
	echo "### ... done!"
	echo ''
done
